package hit.example.detail;

import hit.example.Db.DbAnhViet;
import hit.example.Db.DbRecentFav;
import hit.example.Object.ObjWord;
import hit.example.clipbroad.ActivityClipbroad;
import hit.example.hitdict.R;
import hit.example.home.HomeActivity;
import hit.example.home.RecentFabvoriteFm;
import hit.example.home.TabId;
import java.util.ArrayList;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;

@SuppressLint("ValidFragment")
public class DetailFm extends DetaiFmLayout implements OnClickListener,
		OnInitListener {
	int from;
	public ObjWord obj = null;
	private static String style = "body {color:#FCFBDC;font-size:16px; font-family: Tahoma, Arial, Verdana, serif} * {margin:0px; padding:0px;} ul {padding:1px; margin-left:10px;} li{padding:0px;color:#FF0000;margin-left:10px;} .type{font-weight:bold;font-size:18px;color:#56797F; margin-left:10px;margin-top:5px;} .example {font-weight:bold;color:#FA8000;} .title{font-weight:bold; font-size:18px; color:#000000;} .mexample{color:#003300; font-style:italic;} .aexample{font-weight:bold;color:#00EE00;} .aidiom{font-weight:bold;color:#CC0000;}";
	DbRecentFav db;
	DbAnhViet dbAV;
	public String iCurrentContent;
	public ProgressDialog pd = null;
	TextToSpeech tts;

	public DetailFm() {
		super();
	}

	public DetailFm(ObjWord obj) { // ? co cai from nao day? vua e lam
									// theo cua e nhug nham dai ca
									// lam tiep di.xoa no di :v
		super();
		this.obj = obj;

	}

	// dung roi ma a nhung sang hom activity minh truyen vao dung ko dai ca.
	public void setData(ObjWord obj, int from) {// trường hợp lấy dữ liệu từ
												// listwordfm
		this.obj = obj;
		this.from = from;
	}

	@Override
	public void updateNewData(ArrayList<ObjWord> ojs, int pos) { // trường
																	// howpcj dữ
																	// liệu từ
																	// home
		super.updateNewData(ojs, pos);
		updateDuLieu(ojs.get(0));
		// chap n
	}

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		// wvContent.setBackgroundColor(Color.rgb(159,121,238));
		wvContent.getContentDescription();
		wvContent.getSettings().setJavaScriptEnabled(true);
		txtNghia.setOnClickListener(this);
		txtXalo.setOnClickListener(this);
		imvFav.setOnClickListener(this);
		imvShare.setOnClickListener(this);
		imvSound.setOnClickListener(this);

		initWebView();
		if (obj != null) {
			wvContent.loadDataWithBaseURL(null,
					formatContent(obj.getiContent()), "text/html", "UTF-8",
					null);
			tts = new TextToSpeech(getActivity(), this);
			txtShowResult.setText(obj.getiWord());
			Log.d("dinhtv", obj.getiWord());
			Log.d("dinhtv", obj.getiContent() + "\n --------------");
			iCurrentContent = obj.getiContent().toString();

			updateDuLieu(obj);
		}

	}

	@Override
	public void onDestroy() {
		// Don't forget to shutdown!
		if (tts != null) {
			tts.stop();
			tts.shutdown();
		}
		super.onDestroy();
	}

	@Override
	public boolean onBackPressed() {
		if (from == -1) {
			HomeActivity.getInstance().pusListWordFm();
		} else if (from == 0) {
			HomeActivity.getInstance().pushFragments(TabId.home,
					RecentFabvoriteFm.getInstance(from), true, null);
		} else if (from == 1) {
			HomeActivity.getInstance().pushFragments(TabId.home,
					RecentFabvoriteFm.getInstance(1), true, null);
		} else if (from == 2) {

			ActivityClipbroad.getInstance().pusListWordFm();
		}
		return true;
	}

	private void updateDuLieu(ObjWord obj2) {
		wvContent.loadDataWithBaseURL(null, formatContent(obj2.getiContent()),
				"text/html", "UTF-8", null);
		txtShowResult.setText(obj2.getiWord());
		iCurrentContent = obj2.getiContent().toString();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.idGoogle:
			wvContent.loadUrl("https://www.google.com.vn/");
			break;

		case R.id.idXalo:
			wvContent.loadUrl("http://xalo.vn/");
			break;
		case R.id.idNghia:
			break;
		case R.id.imvFav:
			db = new DbRecentFav(getActivity());

			if (db.getFavCount(txtShowResult.getText().toString()
					.replace("'", "")) == 0) {
				obj = new ObjWord();
				obj.setiWord(txtShowResult.getText().toString()
						.replace("'", ""));
				obj.setiContent(iCurrentContent);
				db.createFavor(obj);
				showToast("Add Favorite Successful");
			} else {
				showToast("Đã tồn tại !");
			}

			break;
		case R.id.imvShare:
			if (from == 2) {
				ActivityClipbroad.getInstance().captureUsingDrawingCache();
			} else {
				HomeActivity.getInstance().captureUsingDrawingCache();
			}
			break;
		case R.id.imvSound:
			speakOut();

			break;
		}
	}

	public String formatContent(String content) {
		StringBuilder htmlData = new StringBuilder();
		htmlData.append("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>");
		if (style != null && !style.equals("")) {
			htmlData.append("<head><style type=\"text/css\"> " + style
					+ " </style></head>");

		}
		htmlData.append("<body><font face=\"Arial\">");

		htmlData.append(content);

		htmlData.append("</font></body></html>");

		return htmlData.toString();
	}

	public void initWebView() {
		wvContent.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				if (pd != null) {
					pd.dismiss();
					pd = null;
				}
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				try {
					String arrUrlPart[] = url.split("://");
					Log.d("dinhtv","shouldOverrideUrlLoading: " + url);
					for(int i = 0; i< arrUrlPart.length; i++){
						Log.d("dinhtv","shouldOverrideUrlLoading: " + i + " = " + arrUrlPart[i]);
					}
					if (arrUrlPart[0].equals("entry")) {
						txtShowResult.setText(arrUrlPart[1]);
						if(mActivity instanceof HomeActivity){
							txtShowResult.setText(arrUrlPart[1]);
							
							Log.d("dinhtv","tu da chon" + arrUrlPart[1]);
							iCurrentContent = getContentByWord(arrUrlPart[1]);
							HomeActivity.getInstance().setEditText(arrUrlPart[1]);
							showContent(iCurrentContent);
						}else {
							iCurrentContent = getContentByWord(arrUrlPart[1]);
							showContent(iCurrentContent);
							
						}
						//
						

					} else if (arrUrlPart[0].equals("http")) {
						try {
							startActivity(new Intent(Intent.ACTION_VIEW, Uri
									.parse(url)));
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
					Log.d("dinhtv","shouldOverrideUrlLoading end");
					/*
					 * String word = url.substring(8, url.length());
					 * showContent(getContentByWord(word));
					 */
				} catch (Exception e) {
					e.printStackTrace();
				}

				return true;
			}
		});

	}

	public void showContent(String content) {
		if (content != null) {
			pd = ProgressDialog.show(getActivity(), "Search", "Loading...");
			wvContent.loadDataWithBaseURL(null, content, "text/html", "UTF-8",
					null);
		}
	}

	public String getContentByWord(String word) {
		String result = null;
		
		dbAV = new DbAnhViet(getActivity());
		
		if (dbAV.getCount(word) > 0) {
			ObjWord obj = new ObjWord();
			obj.setiWord(word);
			iCurrentContent = dbAV.getWordClick(word);
			
			obj.setiContent(iCurrentContent);
			DbRecentFav db = new DbRecentFav(getActivity());
			db.createRecent(obj);
			result = formatContent(iCurrentContent);
		} else {
			result = getResources().getString(R.string.khong_co_tu_nao) + " "
					+ word;
			imvFav.setVisibility(View.GONE);
			imvSound.setVisibility(View.GONE);
		}
		Log.d("dinhtv","ket quaaaaaaaaaaaaaa" + word);
		return result;

	}

	@Override
	public void onInit(int status) {

		if (status == TextToSpeech.SUCCESS) {

			int result = tts.setLanguage(Locale.UK);

			// tts.setPitch(5); // set pitch level

			// tts.setSpeechRate(2); // set speech speed rate

			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
				Log.e("TTS", "Language is not supported");
			} else {
				imvSound.setEnabled(true);
				// speakOut();
			}

		} else {
			Log.e("TTS", "Initilization Failed");
		}

	}

	public void speakOut() {
		String text = txtShowResult.getText().toString();

		tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
	}
	
	@Override
	public void onAttach(Activity activity) {
		mActivity = activity;
		/*mActivity = activity;
		if(mActivity instanceof HomeActivity){
		((HomeActivity)mActivity).pu
		}*/
		
		super.onAttach(activity);
	}
	
	Activity mActivity;

}
